<template>
  <div>
    <!-- 面包导航 -->
    <el-breadcrumb separator="/" style="padding-left:10px;padding-bottom:10px;font-size:12px;">
      <el-breadcrumb-item :to="{ path: '/main' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>物资流向</el-breadcrumb-item>
      <el-breadcrumb-item>物资去处</el-breadcrumb-item>
    </el-breadcrumb>

    <el-card>
      <el-row>
        <el-form size="mini" :inline="true" :model="queryMap" class="demo-form-inline">
          <el-form-item label="省市区县">
            <el-input v-model="queryMap.address" clearable @clear="search" placeholder="省市区县"></el-input>
          </el-form-item>
          <el-form-item label="联系人">
            <el-input v-model="queryMap.contact" clearable @clear="search" placeholder="联系人"></el-input>
          </el-form-item>
          <el-form-item label="具体地点">
            <el-input
                clearable
                v-model="queryMap.name"
                placeholder="请具体地点查询"
                @clear="search"
                class="input-with-el-select"
            ></el-input>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" icon="el-icon-search" @click="search">查询</el-button>
            <el-button type="success" icon="el-icon-circle-plus-outline"
                       @click="openAdd">添加
            </el-button>
          </el-form-item>
        </el-form>
      </el-row>
      <!-- 表格区域 -->
      <el-table
          border
          size="mini"
          v-loading="loading"
          stripe
          :data="consumerData"
          style="width: 100%;"
          height="600"
          max-height="700"
      >
        <el-table-column prop="id"  label="ID" width="50"></el-table-column>
        <el-table-column label="物资去向地址">
          <el-table-column
              prop="address"
              label="省份"
              width="120">
            <template slot-scope="scope">
              <span v-text="scope.row.address.split('/')[0]"></span>
            </template>
          </el-table-column>
          <el-table-column
              prop="address"
              label="市"
              width="120">
            <template slot-scope="scope">
              <span v-text="scope.row.address.split('/')[1]"></span>
            </template>
          </el-table-column>
          <el-table-column
              prop="address"
              label="区县"
              width="100">
            <template slot-scope="scope">
              <span v-text="scope.row.address.split('/')[2]"></span>
            </template>
          </el-table-column>
          <el-table-column
              prop="name"
              label="地址"
              width="200">
          </el-table-column>
        </el-table-column>

        <el-table-column prop="createTime" label="创建时间" width="200"></el-table-column>
        <el-table-column prop="contact" label="联系人" width="200"></el-table-column>
        <el-table-column prop="phone" label="电话" width="140"></el-table-column>
        <el-table-column prop="sort" label="排序" width="100"></el-table-column>
        <el-table-column label="操作" fixed="right">
          <template slot-scope="scope">
            <el-button  type="text" size="mini" icon="el-icon-edit"
                        @click="edit(scope.row)">编辑
            </el-button>

            <el-popconfirm
                @confirm="del(scope.row.id)"
                style="margin-left:10px;"
                confirmButtonText='好的'
                cancelButtonText='不用了'
                icon="el-icon-info"
                iconColor="red"
                title="您确定要删除此供应商信息吗？"
            >
              <el-button type="text" slot="reference" size="mini" icon="el-icon-delete">删除</el-button>
            </el-popconfirm>

          </template>
        </el-table-column>
      </el-table>
      <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="pageNun"
          :page-sizes="[6, 8, 10, 20]"
          :page-size="pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total=total>
      </el-pagination>
    </el-card>
    <!-- 来源添加弹出框 -->
    <el-dialog title="添加来源" :visible.sync="addDialogVisible" width="50%" @close="closeAddDialog">
        <span>
          <el-form
              :model="addRuleForm"
              :rules="addRules"
              ref="addRuleFormRef"
              label-width="100px"
              class="demo-ruleForm"
          >
           <el-row v-if="addRuleForm.id===undefined">
              <el-col :span="8"   >
                <div class="grid-content bg-purple"></div>
                <el-form-item label="省份" prop="valueProvince">
                  <el-select
                      v-model="addRuleForm.valueProvince"
                      placeholder="请选择省"
                      @change="changeProvince"
                  >
                    <el-option
                        v-for="item in provinceList"
                        :key="item.value"
                        :label="item.label"
                        :value="item.value"
                    ></el-option>
                  </el-select>

                </el-form-item>
              </el-col>
              <el-col :span="8">
                <div class="grid-content bg-purple-light">
                  <el-form-item label="城市" prop="valueCity">
                    <el-select
                        v-model="addRuleForm.valueCity"
                        placeholder="请选择市"
                        @change="changeCity"
                    >
                      <el-option
                          v-for="item in cityOptions"
                          :key="item.value"
                          :label="item.label"
                          :value="item.value"
                      ></el-option>
                    </el-select>
                  </el-form-item>
                </div>
              </el-col>
              <el-col :span="8">
                <div class="grid-content bg-purple">
                  <el-form-item label="区县" prop="valueOrigin">
                    <el-select
                        v-model="addRuleForm.valueOrigin"
                        placeholder="请选择区"
                        @change="changeOrigin"
                    >
                      <el-option
                          v-for="item in originOptions"
                          :key="item.label"
                          :label="item.label"
                          :value="item.value"
                      ></el-option>
                    </el-select>
                  </el-form-item>
                </div>
              </el-col>
            </el-row>

                <el-row :span="8"  v-if="addRuleForm.id!==undefined" >
                    <el-form-item label="省市区县" prop="address">
                              <el-input v-model="addRuleForm.address"></el-input>
                </el-form-item>
             </el-row>
            <el-form-item label="详细地址" prop="name">
              <el-input v-model="addRuleForm.name"></el-input>
            </el-form-item>
            <el-form-item label="联系人" prop="contact">
              <el-input v-model="addRuleForm.contact"></el-input>
            </el-form-item>
            <el-form-item label="电话" prop="phone">
              <el-input v-model="addRuleForm.phone"></el-input>
            </el-form-item>
            <el-form-item label="排序" prop="sort">
              <el-input-number v-model="addRuleForm.sort" :min="1" :max="10" label="排序"></el-input-number>
            </el-form-item>
          </el-form>
        </span>
      <span slot="footer" class="dialog-footer">
          <el-button @click="addDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="confirm">确 定</el-button>
        </span>
    </el-dialog>

  </div>
</template>

<script>
import {addSupplier, editSupplier, getJSONDate} from "@/network/business/supplier";
import {addConsumers, deleteConsumers, editConsumers, getConsumers} from "@/network/business/consumers";

export default {
  name: "",
data(){

  var checkPhone = (rule, value, callback) => {
    const phoneReg = /^1[34578]\d{9}$$/;
    if (!value) {
      return callback(new Error("电话号码不能为空"));
    }
    setTimeout(() => {
      // Number.isInteger是es6验证数字是否为整数的方法,实际输入的数字总是识别成字符串
      // 所以在前面加了一个+实现隐式转换
      if (!Number.isInteger(+value)) {
        callback(new Error("请输入数字值"));
      } else {
        if (phoneReg.test(value)) {
          callback();
        } else {
          callback(new Error("电话号码格式不正确"));
        }
      }
    }, 100);
  }
    return{
      queryMap:{},
      originOptions:[],
      cityOptions:[],
      provinceList:[],
      addRuleForm:{},
      consumerData:[],
      pageNun:1,
      pageSize:6,
      total:0,
      loading:true,
      addRules:{  name: [
          { required: true, message: "请输入来源名称", trigger: "blur" },
          { min: 2, max: 50, message: "长度在 2 到 50 个字符", trigger: "blur" }
        ],
        address: [
          { required: true, message: "请输入地址信息" },
          { min: 2, max: 12, message: "长度在 2 到 12 个字符", trigger: "blur" }
        ],
        valueProvince: [
          { required: true, message: "请输入省份", trigger: "change" }
        ],
        valueCity: [{ required: true, message: "请输入城市", trigger: "change" }],
        valueOrigin: [
          { required: true, message: "请输入区县", trigger: "change" }
        ],
        sort: [
          { required: true, message: "请输入排序号", trigger: "change" }
        ],
        contact: [{ required: true, message: "请输入联系人", trigger: "blur" }],
        phone: [
          {
            required: true,
            message: "请输入联系方式",
            validator: checkPhone,
            trigger: "blur"
          }
        ]},
      addDialogVisible:false
    }

},
  methods:{
    confirm(){
      console.log(this.addRuleForm)
      this.$refs['addRuleFormRef'].validate((valid) =>{
        if (!valid) {
          return;
        }else {
          if (this.addRuleForm.id===undefined){
            //添加
            this.addRuleForm.address =
                this.addRuleForm.province +
                "/" +
                this.addRuleForm.city +
                "/" +
                this.addRuleForm.origin;

            console.log(this.addRuleForm.address)
            addConsumers(this.addRuleForm).then((res) => {
              if (res.success===true){
                this.$message.success("添加成功")
                this.getConsumers()
              }else {
                this.$message.error(res.message)
              }
              this.addDialogVisible=false;
            })


          }else {
            /*编辑*/
            editConsumers(this.addRuleForm).then((res) => {
              console.log(res)
              if (res.success===true){
                this.$message.success("编辑成功")
                this.getConsumers()
              }else {
                this.$message.error(res.message)
              }
              this.addDialogVisible=false;

            })
          }
        }
      })

    },
    /*关闭弹窗触犯*/
    closeAddDialog(){
      this.$refs.addRuleFormRef.clearValidate();
      this.addRuleForm={}
    }
    ,
    /*删除*/
    del(id){
      console.log("id:"+id)
      deleteConsumers(id).then((res) => {
        console.log(res)
        if (res.success){
          this.$message.success("删除成功")
        }else {
          this.$message.error(res.message)
        }
      })
    },
    /*编辑*/
    edit(data){
      console.log(data)
      this.addDialogVisible=true
      this.addRuleForm.id=data.id
      this.addRuleForm=data
    },
    /*搜索*/
    search(){
      console.log(this.queryMap)
      this.pageNun=1
      this.getConsumers()
    },
    /*添加*/
    openAdd(){
      this.addDialogVisible=true
    },
  getConsumers(){
      getConsumers(this.pageNun,this.pageSize,this.queryMap).then((res) => {
        if (res.success===true){
          this.consumerData=res.data.list
          this.total=res.data.total
          this.loading=false
        }
        console.log(res)
      })
  }
  ,
    handleSizeChange(val) {
      this.pageSize=val
      this.getConsumers()
    },
    handleCurrentChange(val) {
      this.pageNun=val
      this.getConsumers()    },
    /*选择区*/
    changeOrigin(val){
      this.addRuleForm.valueOrigin = val;
      this.originList.forEach((origin, index) => {
        if (val.toString() === this.originList[index].value) {
          //set value
          this.addRuleForm.origin = this.originList[index].label;
        }
      });
      //添加this.$forceUpdate();进行强制渲染，效果实现。搜索资料得出结果：因为数据层次太多，render函数没有自动更新，需手动强制刷新。
      this.$forceUpdate();
    },
    /*选择市*/
    changeCity(val){
      this.cityList.forEach((city, index) => {
        if (val.toString() === this.cityList[index].value) {
          this.originOptions = this.cityList[index].children;
          this.addRuleForm.valueOrigin = this.cityList[index].children[0].value; //设置县的值;
          //set value
          this.addRuleForm.city = this.cityList[index].label;
        }
      });
    },
    /*选择省*/
    changeProvince(val){
      this.provinceList.forEach((province, index) => {
        if (val.toString() === this.provinceList[index].value) {
          this.cityOptions = this.provinceList[index].children;
          this.addRuleForm.valueCity = this.provinceList[
              index
              ].children[0].value; //设置市的值
          this.addRuleForm.city = this.provinceList[index].children[0].label;
          this.addRuleForm.valueOrigin = this.provinceList[
              index
              ].children[0].children[0].value; //设置县的值
          this.addRuleForm.origin = this.provinceList[
              index
              ].children[0].children[0].label;
          this.originOptions = this.provinceList[index].children[0].children;
          //set value
          this.addRuleForm.province = this.provinceList[index].label;
        }
      });
    },
    getJSONDate(){
      getJSONDate().then((res) => {
        this.provinceList = [];
        this.cityList = [];
        this.originList = [];
        res.forEach(item => {
          if (item.value.match(/0000$/)) {
            this.provinceList.push({
              value: item.value,
              label: item.name,
              children: []
            });
          } else if (item.value.match(/00$/)) {
            this.cityList.push({
              value: item.value,
              label: item.name,
              children: []
            });
          } else {
            this.originList.push({
              value: item.value,
              label: item.name
            });
          }
        });
        for (let index in this.provinceList) {
          for (let index1 in this.cityList) {
            if (
                this.provinceList[index].value.slice(0, 2) ===
                this.cityList[index1].value.slice(0, 2)
            ) {
              this.provinceList[index].children.push(this.cityList[index1]);
            }
          }
        }
        for (let item1 in this.cityList) {
          for (let item2 in this.originList) {
            if (
                this.originList[item2].value.slice(0, 4) ===
                this.cityList[item1].value.slice(0, 4)
            ) {
              this.cityList[item1].children.push(this.originList[item2]);
            }
          }
        }
      });
    }
  },
  created() {
    this.getJSONDate()
    this.getConsumers()
  }
}
</script>

<style scoped>

</style>
